package cn.com.wdjedu.androidapp.wjeduandroid.support.lib.encrypt;

import android.support.annotation.NonNull;
import android.util.Base64;

/**
 * 账号加/解密处理2017/1/13.
 */

public class EncryptAccount implements EncryptBase {

    private static final int ENCRYPT_FLAG = 25432168;

    @Override
    public String encrypt(@NonNull String value) {
        return encrypt(value.getBytes());
    }

    @Override
    public String encrypt(int value) {
        return encrypt(String.valueOf(value));
    }

    @Override
    public String encrypt(long value) {
        return encrypt(String.valueOf(value));
    }

    @Override
    public String encrypt(@NonNull byte[] value) {
        int length = value.length;
        // 每个byte用两个字符才能表示，所以字符串的长度是数组长度的两倍
        StringBuilder sb = new StringBuilder(length * 2);
        for (byte aValue : value) {
            int temp = aValue;
            // 把负数转换为正数
            while (temp < 0) {
                temp = temp + 256;
            }
            // 小于0F的数需要在前面补0
            if (temp < 16) {
                sb.append("0");
            }
            sb.append(Integer.toString(temp, 16));
        }
        return Base64.encodeToString(sb.toString().getBytes(), 0, sb.length(), ENCRYPT_FLAG);
    }

    @Override
    public String decrypt(String value) {
        byte[] bytes = Base64.decode(value, ENCRYPT_FLAG);
        int length = bytes.length;
        // 两个字符表示一个字节，所以字节数组长度是字符串长度除以2
        byte[] output = new byte[length / 2];
        for (int i = 0; i < length; i = i + 2) {
            String strTmp = new String(bytes, i, 2);
            output[i / 2] = (byte) Integer.parseInt(strTmp, 16);
        }
        return new String(output);
    }
}
